package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //转成Http协议模式 (servletRequest里面没有方法)
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

      /*  //0. 禁止远程访问
        String remoteAddr = request.getRemoteAddr();
        System.out.println(remoteAddr);
        if (!remoteAddr.equals("0:0:0:0:0:0:0:1")) {
            return;
        }
*/

        //1.获取路径
        String requestURI = request.getRequestURI();
        //定义不需要过滤的路径
        String [] urls={
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        //抽取方法来进行判断
        boolean flag = check(urls, requestURI);
        //flag为true
        if (flag){
            //表示放行
            filterChain.doFilter(request,response);
            return;
        }
        //2,判断是否已经登录
        Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId!=null){
            //表示已经登录
            BaseContext.setId(empId);
            filterChain.doFilter(request,response);
            return;
        }

        //2,判断是否已经登录
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId!=null){
            //表示已经登录
            BaseContext.setId(userId);
            filterChain.doFilter(request,response);
            return;
        }
        //3,到这里表示未登录(使用fastjson来响应结果)
        String jsonString = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(jsonString);



    }

    private boolean check(String[] urls, String requestURI) {
        //定义通配符比较
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String url : urls) {
            boolean match = antPathMatcher.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}